<?php

/**
 * Component dùng để xác thực facebook
 * 
 * @class       HFBUserIdentity
 * @author      huytbt
 * @version     1.0
 * @date        2011-05-23
 */
class HFBUserIdentity extends CUserIdentity
{
	private $_id;
	
	/**
	 * Phương thức authenticate() dùng để xác thực username và password của User có đúng không
	 *  
	 * @return boolean whether authentication succeeds.
	 */
	public function authenticate()
	{
		try {
			$user = Yii::app()->facebook->getUser();
			if (!$user)
				$this->errorCode = self::ERROR_USERNAME_INVALID;
			else {
				Yii::import('application.modules.facebook.models.FacebookUser');
				$fbuser = FacebookUser::model()->findByAttributes(array('facebook_id'=>$user));
				if (!$fbuser)
					$user = FacebookUser::model()->syncUser();
				else {
					if (time()-intval($fbuser->last_sync) >= Yii::app()->getModule('facebook')->timeForSyncUserInfo)
						$fbuser->syncUserInfo();
					Yii::import('application.modules.user.models.User');
					$user = $fbuser->user;
				}
				if ($user) {
					$this->_id = $user->id;
					$this->setState('model', $user);
					$this->errorCode = self::ERROR_NONE;
				} else
					$this->errorCode = self::ERROR_USERNAME_INVALID;
			}
		} catch(Exception $e) {
			$this->errorCode = self::ERROR_USERNAME_INVALID;
		}
		
		return !$this->errorCode;
	}
	
	public function getId()
	{
		return $this->_id;
	}
}
